﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ext.Net.MVC;
using FreedomERP.Models;
using FreedomERP.Services.Bd.Impl;
using System.Web.Routing;
using FreedomERP.Comm;
using FreedomERP.Models.Bd;
using Newtonsoft.Json;
using FreedomERP.Models.Sd;
using FreedomERP.Services.Sd;
using FreedomERP.Services.Sd.Impl;
using FreedomERP.Comm.Utils;
using System.Collections;
using Ext.Net;
using FreedomERP.Filter;

namespace FreedomERP.Controllers
{
    [CheckSessionFilterAttribute]
    public class SaleOrderController : Controller
    {
        IBdCategoryService categoryService { get; set; }
        ISdSaleOrderService saleOrderService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (categoryService == null)
            {
                categoryService = new BdCategoryServiceImpl();
            }
            if (saleOrderService == null) 
            {
                saleOrderService = new SdSaleOrderServiceImpl();
            }
            base.Initialize(requestContext);
        }

        /// <summary>
        /// 出货扫描
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public ActionResult SendBarcodeScan()
        {
            return View();
        }

        /// <summary>
        /// 安装扫描
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public ActionResult InstallBarcodeScan()
        {
            return View();
        }

        /// <summary>
        /// 销售订单列表
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public ActionResult SaleOrderIndex()
        {
            return View();
        }

        /// <summary>
        /// 获取销售类型
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public AjaxStoreResult GetSaleOrderBillTypeList()
        {
            List<BdCategory> categoryList = categoryService.QueryCategoryListByFType(ConstData.CATEGORY_SALE_ORDER_BILL_TYPE);

            List<BdCategoryView> listView = new List<BdCategoryView>();

            if (categoryList != null)
            {
                foreach (BdCategory category in categoryList)
                {
                    BdCategoryView categoryView = new BdCategoryView();
                    categoryView.FID = category.FId;
                    categoryView.FName = category.FName;
                    listView.Add(categoryView);
                }
            }

            return new AjaxStoreResult(listView, listView.Count);
        }

        /// <summary>
        /// 保存销售单信息
        /// </summary>
        /// <param name="msg">JSON字符串</param>
        /// <author>梁建东</author>
        /// <returns></returns>
        public AjaxResult SaveSaleOrderMsg(string msg)
        {
            AjaxResult response = new AjaxResult();
            try
            {
                string FId = "";
                string currAccountFId = BaseController.GetCurrLoginAccountFId();
                string currOrgunitFId = BaseController.GetCurrLoginOrgunitFId();

                SdSaleOrderView saleOrderView = JsonConvert.DeserializeObject<SdSaleOrderView>(msg);
                if (saleOrderView.FBusinessCategoryId == "")
                    saleOrderView.FBusinessCategoryId = null;
                if (saleOrderView.FId == null || saleOrderView.FId.Trim().Equals(""))
                {
                    saleOrderService.AddSaleOrder(saleOrderView, currAccountFId, currOrgunitFId, out FId);
                }
                else
                {
                    saleOrderService.ModifySaleOrder(saleOrderView, currAccountFId);
                    FId = saleOrderView.FId;
                }
                response.Result = FId;
            }
            catch (Exception e)
            {
                response.ErrorMessage = e.Message;
            }
            return response;
        }

        /// <summary>
        /// 获取订单明细
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public AjaxStoreResult GetSaleOrderDetailListByFParentId(string FParentId)
        {
            List<SdSaleOrderDetailView> listView = new List<SdSaleOrderDetailView>();
            List<SdSaleOrderDetail> list = saleOrderService.GetSaleOrderDetailListByFParentId(FParentId);
            if (list != null)
            {
                foreach (SdSaleOrderDetail detail in list)
                {
                    SdSaleOrderDetailView objView = new SdSaleOrderDetailView();
                    objView.FId = detail.FId;
                    objView.FParentId = detail.FParentId;
                    objView.FBarcode = detail.FBarcode;

                    listView.Add(objView);
                }
            }
            return new AjaxStoreResult(listView, listView.Count);
        }

        /// <summary>
        /// 获取订单信息
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public AjaxStoreResult GetSaleOrderMsgByFId(string FId)
        {
            List<SdSaleOrderView> list = new List<SdSaleOrderView>();
            SdSaleOrder obj = saleOrderService.GetSaleOrderByFId(FId);
            if (obj != null)
            {
                SdSaleOrderView objView = new SdSaleOrderView();
                objView.FId = obj.FId;
                objView.FNumber = obj.FNumber;
                objView.FBillDate = DateUtils.FormatDate(obj.FBillDate, "yyyy-MM-dd");
                objView.FBusinessCategoryId = obj.FBusinessCategoryId;
                objView.FCustomerName = obj.FCustomerName;
                objView.FCustomerPhone = obj.FCustomerPhone;
                objView.FCustomerMobile = obj.FCustomerMobile;
                objView.FCustomerAddress = obj.FCustomerAddress;
                objView.FCreateTime = obj.FCreateTime.ToString();
                objView.FCreatorId = obj.BdAccount1 == null ? "" : obj.BdAccount1.FAccount;
                objView.FModifyTime = obj.FModifyTime.ToString();
                objView.FModifierId = obj.BdAccount2 == null ? "" : obj.BdAccount2.FAccount;
                objView.FApproveTime = obj.FApproveTime == null ? "" : obj.FApproveTime.ToString();
                objView.FApproverId = obj.BdAccount == null ? "" : obj.BdAccount.FAccount;
                objView.FStatusId = obj.FStatusId;
                objView.FRemark = obj.FRemark;

                list.Add(objView);
            }
            return new AjaxStoreResult(list, list.Count);
        }

        /// <summary>
        /// 审核订单
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public AjaxResult ApproveOrder(string FId)
        {
            AjaxResult response = new AjaxResult();
            try
            {
                string currAccountFId = BaseController.GetCurrLoginAccountFId();
                saleOrderService.ApproveSaleOrder(FId, currAccountFId);
            }
            catch (Exception e)
            {
                response.ErrorMessage = e.Message;
            }
            return response;
        }

        /// <summary>
        /// 反审核订单
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public AjaxResult UnApproveSaleOrder(string FId)
        {
            AjaxResult response = new AjaxResult();
            try
            {
                string currAccountFId = BaseController.GetCurrLoginAccountFId();
                saleOrderService.UnApproveSaleOrder(FId, currAccountFId);
            }
            catch (Exception e)
            {
                response.ErrorMessage = e.Message;
            }
            return response;
        }

        /// <summary>
        /// 根据条码获取销售记录
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public AjaxResult GetSaleOrderByFBarcode(string FBarcode)
        {
            AjaxResult response = new AjaxResult();
            try
            {
                string FStatusId = categoryService.QueryCategoryFIdByFTypeAndFNumber(ConstData.CATEGORY_COMM_ORDER_STATUS, ConstData.COMM_ORDER_STATUS_APPROVE);
                string FBusinessCategoryId = categoryService.QueryCategoryFIdByFTypeAndFNumber(ConstData.CATEGORY_SALE_ORDER_BILL_TYPE, ConstData.SALE_ORDER_BILL_TYPE_WHOLESALE);
                string currAccountOrgunitId = BaseController.GetCurrLoginAccountOrgunitFId();

                int tatalCount = 0;

                Hashtable filters = new Hashtable();
                filters.Add("FStatusId", FStatusId);
                filters.Add("FBusinessCategoryId", FBusinessCategoryId);
                filters.Add("FBarcode", FBarcode);
                filters.Add("orgunitParam", currAccountOrgunitId);

                PagingParams pgp = new PagingParams("FCreateTime", OrderDirection.ToDirection("DESC"), 0, ConstData.COMM_LIST_PAGE_SIZE, filters);
                List<SdSaleOrder> saleOrderList = saleOrderService.QuerySaleOrderPaggingByParam(pgp,out tatalCount);
                if (saleOrderList != null && saleOrderList.Count > 0)
                {
                    SdSaleOrder saleOrder = saleOrderList.First<SdSaleOrder>();

                    Parameter pFNumber = new Parameter();
                    pFNumber.Name = "FNumber";
                    pFNumber.Value = saleOrder.FNumber;
                    response.ExtraParamsResponse.Add(pFNumber);

                    Parameter pFBillDate = new Parameter();
                    pFBillDate.Name = "FBillDate";
                    pFBillDate.Value = DateUtils.FormatDate(saleOrder.FBillDate, "yyyy-MM-dd");
                    response.ExtraParamsResponse.Add(pFBillDate);

                    Parameter pFCustomerName = new Parameter();
                    pFCustomerName.Name = "FCustomerName";
                    pFCustomerName.Value = saleOrder.FCustomerName;
                    response.ExtraParamsResponse.Add(pFCustomerName);

                    Parameter pFCustomerPhone = new Parameter();
                    pFCustomerPhone.Name = "FCustomerPhone";
                    pFCustomerPhone.Value = saleOrder.FCustomerPhone;
                    response.ExtraParamsResponse.Add(pFCustomerPhone);

                    Parameter pFCustomerMobile = new Parameter();
                    pFCustomerMobile.Name = "FCustomerMobile";
                    pFCustomerMobile.Value = saleOrder.FCustomerMobile;
                    response.ExtraParamsResponse.Add(pFCustomerMobile);

                    Parameter pFCustomerAddress = new Parameter();
                    pFCustomerAddress.Name = "FCustomerAddress";
                    pFCustomerAddress.Value = saleOrder.FCustomerAddress;
                    response.ExtraParamsResponse.Add(pFCustomerAddress);

                    Parameter pResult = new Parameter();
                    pResult.Name = "Result";
                    pResult.Value = "true";
                    response.ExtraParamsResponse.Add(pResult);
                }
                else
                {
                    Parameter pResult = new Parameter();
                    pResult.Name = "Result";
                    pResult.Value = "false";
                    response.ExtraParamsResponse.Add(pResult);
                }
            }
            catch (Exception e)
            {
                response.Result = false;
                response.ErrorMessage = e.Message;
                return response;
            }
            return response;
        }

        /// <summary>
        /// 销售订单分页列表
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public AjaxStoreResult SaleOrderListPaging(int start, int limit, string dir, string sort, string FNumberParam, string FBillDateFrom, string FBillDateTo, string FStatusId, string FBusinessCategoryId, string FBarcode)
        {
            int tatalCount = 0;

            string currAccountOrgunitFId = BaseController.GetCurrLoginAccountOrgunitFId();

            Hashtable filters = new Hashtable();
            filters.Add("FNumberParam", FNumberParam);
            filters.Add("FBillDateFrom", FBillDateFrom);
            filters.Add("FBillDateTo", FBillDateTo);
            filters.Add("FStatusId", FStatusId);
            filters.Add("FBusinessCategoryId", FBusinessCategoryId);
            filters.Add("FBarcode", FBarcode);
            filters.Add("orgunitParam", currAccountOrgunitFId);

            PagingParams pgp = new PagingParams(sort, OrderDirection.ToDirection(dir), start, limit, filters);

            List<SdSaleOrder> listTemp = saleOrderService.QuerySaleOrderPaggingByParam(pgp, out tatalCount);

            List<SdSaleOrderView> listNew = new List<SdSaleOrderView>();
            foreach (SdSaleOrder objTemp in listTemp)
            {
                SdSaleOrderView objView = new SdSaleOrderView();
                objView.FId = objTemp.FId;
                objView.FNumber = objTemp.FNumber;
                objView.FBillDate = DateUtils.FormatDate(objTemp.FBillDate, "yyyy-MM-dd");
                objView.FCreateTime = objTemp.FCreateTime.ToString();
                objView.FCreatorId = objTemp.BdAccount1 == null ? "" : objTemp.BdAccount1.FAccount;
                objView.FStatusId = objTemp.BdCategory1==null?"":objTemp.BdCategory1.FName;
                objView.FBusinessCategoryId = objTemp.BdCategory == null ? "" : objTemp.BdCategory.FName;
                listNew.Add(objView);
            }
            AjaxStoreResult pagingResult = new AjaxStoreResult(listNew, tatalCount);
            return pagingResult;
        }

        /// <summary>
        /// 销售订单状态列表
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public AjaxStoreResult GetSaleOrderStatusList()
        {
            List<BdCategory> categoryList = categoryService.QueryCategoryListByFType(ConstData.CATEGORY_COMM_ORDER_STATUS);

            List<BdCategoryView> listView = new List<BdCategoryView>();

            if (categoryList != null)
            {
                foreach (BdCategory category in categoryList)
                {
                    BdCategoryView categoryView = new BdCategoryView();
                    categoryView.FID = category.FId;
                    categoryView.FName = category.FName;
                    listView.Add(categoryView);
                }
            }

            return new AjaxStoreResult(listView, listView.Count);
        }
    }
}
